package com.example.demo;


import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.web.HttpRequestHandler;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.SessionAttribute;

@RestController
@RequestMapping("/testkkk")
public class ReuestConteoller1 {

    @RequestMapping("/getcookie")
    public String getcookie(HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        if(cookies != null) {
            for (Cookie cookie : cookies) {
                System.out.println(cookie.getName() + ":" + cookie.getValue());
            }
        }
        return "获取cookie成功";
    }

    @RequestMapping("/getcookie2")
    public String getcookie2(@CookieValue("name") String request) {

        return "获取cookie成功,CookieName:" + request;
    }

    @RequestMapping("/setsession")
    public String setsession(HttpServletRequest request,String name) {
        //String name 用于获取发送http请求的用户名
        //从cookie中获取sessionid, 并根据sessionID获取httpSession对象
        //没有session时, 就会创建一个session
        HttpSession session = request.getSession();

        //设置用户信息
        session.setAttribute("name",name);
        session.setAttribute("age",22);
        return "设置session成功";
    }

    @RequestMapping("/getsession")
    public String getSession(HttpServletRequest request){
        //从cookie中获取sessionid, 并根据sessionID获取httpSession对象
        //没有session时, 就会创建一个session
        HttpSession session = request.getSession();
        //获取用户信息
        String name = (String)session.getAttribute("name");
        Integer age = (Integer) session.getAttribute("age");
        return "从session中获取数据, name:"+ name + ",age:"+ age;
    }

    //方式二
    @RequestMapping("/getsession2")
    public String getsession2(HttpSession session) {
        //获取用户信息
        String name = (String)session.getAttribute("name");
        Integer age = (Integer) session.getAttribute("age");
        return "从session中获取数据, name:"+ name + ",age:"+ age;
    }

    //方式三
    @RequestMapping("/getsession3")
    public String getSession3(@SessionAttribute("name") String name){
        //获取用户信息
        return "从session中获取数据, name:"+ name;
    }

}
